package com.base.core.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ消息队列配置类
 * 用于声明活动(Campaign)相关的交换机、队列及绑定关系
 */
@Configuration
public class RabbitMQConfig {

    // 活动消息队列名称
    public static final String CAMPAIGN_QUEUE = "campaign.queue";
    // 活动消息交换机名称
    public static final String CAMPAIGN_EXCHANGE = "campaign.exchange";
    // 活动消息路由键
    public static final String CAMPAIGN_ROUTING_KEY = "campaign.routing.key";

    /**
     * 创建活动主题交换机
     * 主题交换机类型允许根据路由键模式匹配来路由消息
     * @return TopicExchange 主题交换机实例
     */
    @Bean
    public TopicExchange campaignExchange() {
        return new TopicExchange(CAMPAIGN_EXCHANGE);
    }

    /**
     * 创建活动消息队列
     * @return Queue 队列实例
     * 参数说明：
     *   - durable=true 表示队列持久化，RabbitMQ服务重启后队列仍然存在
     *   - exclusive=false 表示非独占队列，允许多个消费者连接
     *   - autoDelete=false 表示不自动删除队列，需要显式删除
     */
    @Bean
    public Queue campaignQueue() {
        return new Queue(CAMPAIGN_QUEUE, true);
    }

    /**
     * 创建队列与交换机的绑定关系
     * @return Binding 绑定关系实例
     * 作用说明：
     *   将campaignQueue队列绑定到campaignExchange交换机，
     *   并使用CAMPAIGN_ROUTING_KEY作为路由键
     */
    @Bean
    public Binding campaignBinding() {
        return BindingBuilder.bind(campaignQueue())
                .to(campaignExchange())
                .with(CAMPAIGN_ROUTING_KEY);
    }
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}